package com.example.ruiji.controller.user;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.ruiji.dao.mapper.UserMapper;
import com.example.ruiji.pojo.User;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Base64;

/**
 * Author:BaiYiChen
 * Date:2022/5/1 10:12
 *
 * @author BaiYiChen
 */
@RestController
@RequestMapping(value = "/usr",produces = "application/json;charset=utf-8")
public class UserController {
  @Autowired
  private UserMapper userMapper;
  @GetMapping("/avatat.do")
  public byte[] getAvat(@RequestParam("aId") Integer id){
    LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
    wrapper.select(User::getAvatar).eq(User::getId,id);
    User user = userMapper.selectOne(wrapper);
    return user.getAvatar();
  }
  @GetMapping("/do/{aId}")
  public void get(@PathVariable("aId")Integer id, HttpServletResponse resp) throws IOException {
    LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
    wrapper.select(User::getAvatar).eq(User::getId,id);
    User user = userMapper.selectOne(wrapper);
    byte[] avatar = user.getAvatar();
    resp.setContentType("image/jpeg");
    resp.setCharacterEncoding("UTF-8");
    OutputStream respOutputStream = resp.getOutputStream();
    InputStream byteArrayInputStream = new ByteArrayInputStream(avatar);
    int len=0;
    byte[] buffer = new byte[1024];
    while ((len=byteArrayInputStream.read(buffer, 0, 1024))!=-1){
      respOutputStream.write(buffer,0,len);
    }
    respOutputStream.close();
  }
}
